package gw.com.android.ui.quote2.editquote;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.quote2.widget.OnStartDragListener;
import gw.com.android.ui.quote2.widget.SimpleItemTouchHelperCallback;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.model.DataItemDetail;
import www.com.library.util.NetworkMonitor;
import www.com.library.view.BtnClickListener;
import www.com.library.view.TintImageTextView;

/**
 * 编辑自选产品
 * Created by jay on 2017/8/17.
 */

public class EditOptionalActivity extends BaseActivity implements OnStartDragListener {
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.checkbox)
    TintImageTextView checkbox;
    @BindView(R.id.del_optional)
    TextView delOptional;
    @BindView(R.id.empty_icon)
    TintImageTextView mEmptyIcon;
    private ItemTouchHelper mItemTouchHelper;
    private OptionalListAdapter OptionalAdapter;
    private boolean isChange = false;
    private int mCount = 0;//已选中的item数目

    @Override
    protected int getLayoutView() {
        return R.layout.activity_edit_aptional_layout;
    }

    @Override
    protected void initLayoutView() {
        ButterKnife.bind(this);
        mTitleBar.setAppTitle(AppMain.getAppString(R.string.quote_title_edit_product));
//        mTitleBar.setLeftText(R.string.optional_title_left);
        mTitleBar.setRightText(R.string.optional_title_left);
        mTitleBar.setBtnClickListener(new BtnClickListener() {
            @Override
            public void onBtnClick(int viewID) {
                switch (viewID) {
                    case R.id.title_left_icon:
                    case R.id.title_right_text:
                        finish();
                        MobclickEventUtlis.MobclickEventByAccountType(EditOptionalActivity.this, "ClickSearch5");
                        break;
                }

            }
        });
        delOptional.setEnabled(false);
        delOptional.setTextColor(ColorThemeUtil.instance().color_f);
        delOptional.setText(AppMain.getAppString(R.string.optional_title_del_disable));
        recyclerView.setHasFixedSize(true);
        // 线性布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        // 设置布局管理器
        recyclerView.setLayoutManager(linearLayoutManager);
//        recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.common_divider_left20_bg));
    }

    @Override
    protected void initViewData() {
        OptionalAdapter = new OptionalListAdapter(this, this);
        recyclerView.setAdapter(OptionalAdapter);
        if (OptionalAdapter.getItemCount() > 0) {
            mEmptyIcon.setVisibility(View.GONE);
        } else {
            mEmptyIcon.setVisibility(View.VISIBLE);
        }
        mEmptyIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityManager.showQuoteSelfAddActivity(EditOptionalActivity.this);
            }
        });
        ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(OptionalAdapter);
        mItemTouchHelper = new ItemTouchHelper(callback);
        mItemTouchHelper.attachToRecyclerView(recyclerView);
        checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!checkbox.isSelected()) {
                    isChange = false;
                    OptionalAdapter.setTickSelected(true);
                    mCount = OptionalAdapter.getItemCount();
                    checkbox.setSelected(true);
                    checkbox.setImageResource(R.mipmap.a_quote_choose);
                    checkbox.setImageColorValue(getResources().getColor(R.color.color_w), getResources().getColor(R.color.color_w));
                } else {
                    if (!isChange) {
                        OptionalAdapter.setTickSelected(false);
                        mCount = 0;
                    } else {
                        mCount = OptionalAdapter.TickListSelected();
                    }
                    checkbox.setSelected(false);
                    checkbox.setImageResource(R.mipmap.a_quote_editunchoose);
                    checkbox.setImageColorValue(getResources().getColor(R.color.color_ccccccc), getResources().getColor(R.color.color_ccccccc));
                }
                flushDelBtn(mCount);
            }
        });

        delOptional.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!NetworkMonitor.hasNetWork()) {
                    return;
                }

                OptionalAdapter.OnTickListRemove();
                delOptional.setEnabled(false);
                delOptional.setTextColor(ColorThemeUtil.instance().color_f);
                delOptional.setText(AppMain.getAppString(R.string.optional_title_del_disable));
                checkbox.setSelected(false);
                checkbox.setImageResource(R.mipmap.a_quote_editunchoose);
                checkbox.setColorValue(ColorThemeUtil.instance().color_c, ColorThemeUtil.instance().color_c);
                if (OptionalAdapter.getItemCount() > 0) {
                    mEmptyIcon.setVisibility(View.GONE);
                } else {
//                    mEmptyIcon.setVisibility(View.VISIBLE);//你就不要出现了，在这个版本，很容易让人觉得app闪烁了一下
                }
                //如果是删除所有，则直接finish
                if (mCount == DataManager.instance().getSelfTickList().getDataCount()) {//???所有item的总数在哪里
                    AppMain.getApp().getHandler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();//如果你是要全选删除，那我就直接返回了
                            new ToastPopWindow(EditOptionalActivity.this, getString(R.string.no_pro_self)).show();
                        }
                    }, 0);
                }
                if (null != OptionalAdapter) {
                    OptionalAdapter.saveSelfData();
                }
                AppTerminal.instance().saveCustomer(DataManager.instance().getSelfCodes());
                //全选删除?记得通知NewQuoteFragment
                RxBus.getInstance().post(GTSConst.REPLY_SWITCH_QUOTE_EDIT_BTN, false);

                MobclickEventUtlis.MobclickEventByAccountType(EditOptionalActivity.this, "ClickDelete2");
            }
        });

        OptionalAdapter.setOnItemClickListener(new OptionalListAdapter.ItemClickListener() {
            @Override
            public void onItemClick(int mapSize) {
                mCount = mapSize;
                if (mapSize < OptionalAdapter.getItemCount()) {
                    isChange = true;
                    checkbox.setSelected(false);
                    checkbox.setImageResource(R.mipmap.a_quote_editunchoose);
                    checkbox.setImageColorValue(getResources().getColor(R.color.color_ccccccc), getResources().getColor(R.color.color_ccccccc));
                } else {
                    checkbox.setSelected(true);
                    isChange = false;
                    checkbox.setImageResource(R.mipmap.a_quote_choose);
                    checkbox.setImageColorValue(getResources().getColor(R.color.color_w), getResources().getColor(R.color.color_w));
                }

                flushDelBtn(mCount);
            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder holder, int position) {

            }
        });
    }

    private void flushDelBtn(int selectionSize) {
        if (selectionSize > 0) {
            delOptional.setEnabled(true);
            delOptional.setTextColor(ColorThemeUtil.instance().color_f);
            delOptional.setBackgroundResource(R.drawable.common_big_btn_bg2);
            delOptional.setText(AppMain.getAppString(R.string.optional_title_del, mCount + ""));//白字，蓝底

        } else {
            delOptional.setEnabled(false);
            delOptional.setTextColor(ColorThemeUtil.instance().color_f);
            delOptional.setBackgroundResource(R.drawable.common_big_btn_bg3);
            delOptional.setText(AppMain.getAppString(R.string.optional_title_del_disable));
        }
    }

    /**
     * 刷新界面ui
     */
    private void refreshView() {
        if (null != OptionalAdapter) {
            OptionalAdapter.refreshData();
            if (OptionalAdapter.getItemCount() > 0) {
                mEmptyIcon.setVisibility(View.GONE);
            } else {
//                mEmptyIcon.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void registerRxBus() {
        Disposable quoteListRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_SYMBOL_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        refreshView();
                    }
                });

        bindSubscription(quoteListRegister);

        Disposable quoteUpdateRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail model) throws Exception {
                        refreshView();
                    }
                });

        bindSubscription(quoteUpdateRegister);

        Disposable quoteSelfRegister = RxBus.getInstance().register(GTSConst.REPLY_QUOTE_SELF, DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail model) throws Exception {
                        if (null != OptionalAdapter && null != model) {
                            if (model.getInt(GTSConst.JSON_KEY_ISSELECTED) == 1) {
                                OptionalAdapter.addQuoteItem(model);
                            } else {
                                OptionalAdapter.removeQuoteItem(model.getInt(GTSConst.JSON_KEY_CODEID));
                                if (mCount > 0) {
                                    mCount--;
                                    flushDelBtn(mCount);
                                }
                            }
                            if (OptionalAdapter.getItemCount() > 0) {
                                mEmptyIcon.setVisibility(View.GONE);
                            } else {
//                                mEmptyIcon.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                });

        bindSubscription(quoteSelfRegister);

        Disposable positionListRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_POSTION_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        Logger.i("持仓列表刷新MainActivity 持仓列表回包接收到回调");
                        refreshView();
                    }
                });
        bindSubscription(positionListRegister);
    }

    @Override
    protected void onResume() {
        super.onResume();
        onSendQuote();
    }

    @Override
    public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
        mItemTouchHelper.startDrag(viewHolder);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == AppContances.RESULT_CODE) {
            Logger.e("EditOptionalActivity 交易界面直接返回到主面板 ");
            setResult(AppContances.RESULT_CODE);
            finish();
        }
    }
}
